package org.springframework.boot.netty.argumentResolver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.netty.listener.Message;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;

import java.util.List;

/**
 * Author: huoxingzhi
 * Date: 2021/1/14
 * Email: hxz_798561819@163.com
 */
public class ThrowableResolverComposite implements ThrowableResolver {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private List<ThrowableResolver> throwableResolvers;

    public ThrowableResolverComposite(List<ThrowableResolver> throwableResolvers) {
        this.throwableResolvers = throwableResolvers;
        AnnotationAwareOrderComparator.sort(throwableResolvers);
    }

    @Override
    public boolean supportsThrowable(Exception e){

        for (ThrowableResolver throwableResolver : this.throwableResolvers) {
            if(throwableResolver.supportsThrowable(e)){
                return true;
            }
        }

        return false;
    }

    @Override
    public void resolveException(Message message, Exception e) {
        ThrowableResolver candicateThrowableResolver = findCandicateThrowableResolver(e);
        if(null==candicateThrowableResolver){
            printExceprion(e);
        }
        candicateThrowableResolver.resolveException(message,e);

    }

    private ThrowableResolver findCandicateThrowableResolver(Exception e){
        for (ThrowableResolver throwableResolver : this.throwableResolvers) {
            if(throwableResolver.supportsThrowable(e)){
                return throwableResolver;
            }
        }

        return null;
    }

    private void printExceprion(Exception e){

        logger.info("{}-->{}",getClass(),e.getMessage());

        if(logger.isDebugEnabled()){
            e.printStackTrace();
        }
    }

}
